<?php
/**
+-----------------------------------------------------------------------------------------------
* GouGuOPEN [ 左手研发，右手开源，未来可期！]
+-----------------------------------------------------------------------------------------------
* @Copyright (c) 2021~2024 http://www.gouguoa.com All rights reserved.
+-----------------------------------------------------------------------------------------------
* @Licensed 勾股OA，开源且可免费使用，但并不是自由软件，未经授权许可不能去除勾股OA的相关版权信息
+-----------------------------------------------------------------------------------------------
* @Author 勾股工作室 <hdm58@qq.com>
+-----------------------------------------------------------------------------------------------
*/

declare (strict_types = 1);

namespace app\lawcase\model;

use think\Model;
use think\facade\Db;
use think\facade\Log;

class LawcaseProgress extends Model
{
    protected $name = 'lawcase_progress';
    protected $prefix = 'oa_';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';
    
    protected $type = [
        'attachment_ids' => 'json'
    ];

    /**
     * 添加案件进度
     * @param array $param
     * @return array
     */
    public function addProgress(array $param)
    {
        try {
            $param['create_time'] = time();
            $insertId = self::strict(false)->field(true)->insertGetId($param);
            add_log('add', $insertId, $param);
        } catch (\Exception $e) {
            return ['code' => 1, 'msg' => '添加失败：' . $e->getMessage()];
        }
        return to_assign(0,'操作成功',['return_id'=>$insertId]);
    }

    /**
     * 编辑案件进度
     * @param array $param
     * @return array
     */
    public function editProgress(array $param)
    {
        try {
            $param['update_time'] = time();
            $this->strict(false)->where('id', $param['id'])->update($param);
            add_log('edit', $param['id'], $param);
        } catch (\Exception $e) {
            return ['code' => 1, 'msg' => '编辑失败：' . $e->getMessage()];
        }
        return to_assign(0,'操作成功',['return_id'=>$param['id']]);
    }

    /**
     * 删除案件进度
     * @param int $id
     * @return array
     */
    public function removeProgress(int $id)
    {
        try {
            $param['delete_time'] = time();
            $this->strict(false)->where('id', $id)->update(['delete_time'=>time()]);
            add_log('delete', $id);
        } catch(\Exception $e) {
            return to_assign(2, '操作失败，原因：'.$e->getMessage());
        }
        return to_assign();
    }

    /**
     * 获取单个案件进度信息
     * @param int $id
     * @return array|null
     */
    public function getProgress(int $id)
    {
        $progress = $this->where('id', $id)->find();
        if ($progress) {
            return ['code' => 0, 'msg' => '获取成功', 'data' => $progress->toArray()];
        } else {
            return ['code' => 1, 'msg' => '案件进度信息不存在'];
        }
    }

    /**
     * 获取案件进度列表
     * @param array $where 基础查询条件
     * @param array $param 搜索参数
     * @return 	hink\Paginator
     */
    public function getList($where = [], $param = [])
    {
        $query = $this->alias('lp')
        ->leftJoin('oa_lawcase lc', 'lp.case_id = lc.id')
        ->leftJoin('oa_admin admin', 'lp.operator = admin.id')
        ->leftJoin('oa_lawcase_party cp', 'lc.id = cp.case_id AND cp.is_client = 1 AND cp.delete_time = 0')
        ->leftJoin('oa_party p', 'cp.party_id = p.id')
        ->field('lp.*, lc.case_code as case_number, admin.name as operator_name, p.name as party_name')
        ->where('lp.delete_time', 0);
        
        if (!empty($where['case_id'])) {
            $query->where('lp.case_id', $where['case_id']);
        }
        
        if (!empty($param['case_number'])) {
            $query->where('lc.case_code', 'like', '%' . $param['case_number'] . '%');
        }
        
        if (!empty($param['event_type'])) {
            $query->where('lp.event_type', $param['event_type']);
        }
        
        if (!empty($param['operator'])) {
            $query->where('lp.operator', $param['operator']);
        }
        
        $page = $param['page'] ?? 1;
        $limit = $param['limit'] ?? 15;
        
        $result = $query->order('lp.create_time desc')
        ->paginate(['list_rows' => $limit, 'page' => $page]);

        // 处理数据格式
        $data = $result->toArray();
        $list = $data['data'];
        
        // 按案件进度ID分组处理委托人信息
        $groupedData = [];
        foreach($list as $item) {
            if(!isset($groupedData[$item['id']])) {
                $groupedData[$item['id']] = $item;
                $groupedData[$item['id']]['party_names'] = [];
            }
            if(!empty($item['party_name'])) {
                $groupedData[$item['id']]['party_names'][] = $item['party_name'];
            }
        }
        
        return [
            'code' => 0,
            'msg' => '',
            'data' => [
                'count' => $data['total'],
                'data' => array_values($groupedData)
            ]
        ];
    }
}